using System;
using UnityEngine;
using QFramework;

namespace ProjectSurvival
{
    public partial class PickAllExp : GamePlayObject
    {
        [SerializeField] private float moveSpeed = 10f;

        private Collider2D _collider;

        private void Awake()
        {
            _collider = GetComponent<Collider2D>();
        }
        private void OnTriggerEnter2D(Collider2D other)
        {
            if (other.GetComponent<CollectableArea>())
            {
                var exps = Transform.FindObjectsByType<Exp>(FindObjectsInactive.Exclude, FindObjectsSortMode.None);
                foreach (var exp in exps)
                {
                    ActionKit.OnUpdate.Register(() =>
                    {
                        if (Player.Instance)
                        {
                            var direction = (Player.Instance.transform.position - exp.transform.position).normalized;
                            exp.transform.Translate(direction * Time.deltaTime * moveSpeed);
                        }
                    }).UnRegisterWhenGameObjectDestroyed(exp.gameObject);
                }
                var coins = Transform.FindObjectsByType<Coin>(FindObjectsInactive.Exclude, FindObjectsSortMode.None);
                foreach (var coin in coins)
                {
                    ActionKit.OnUpdate.Register(() =>
                    {
                        if (Player.Instance)
                        {
                            var direction = (Player.Instance.transform.position - coin.transform.position).normalized;
                            coin.transform.Translate(direction * Time.deltaTime * moveSpeed);
                        }
                    }).UnRegisterWhenGameObjectDestroyed(coin.gameObject);
                }

                AudioKit.PlaySound("GetAllExp");
                gameObject.DestroySelfGracefully();
            }
        }

        protected override Collider2D Collider => _collider;
    }
}